package com.pic4493.updater;

import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.net.NetClientJ;
import com.pic4493.utils.UtiDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class TaskCheckVersion extends AsyncTask<Object, Object, Object>
{
   private String versionName;
   private Context context;
   private UpdateInfo info;
   private boolean isShowDialog = false;

   public TaskCheckVersion(Context _context)
   {
	  context = _context;
   }

   public TaskCheckVersion(Context _context, boolean _isShowDialog)
   {
	  context = _context;
	  isShowDialog = _isShowDialog;
   }

   @Override
   protected void onPreExecute()
   {
	  if (isShowDialog)
	  {
		 UtiDialog.getInstance().ShowLoadingDialogNoTitle(context, "检查更新中请稍候...");
	  }
   }

   @Override
   protected Object doInBackground(Object... params)
   {
	  return NetClientJ.CheckNewVersion();
   }

   @Override
   protected void onPostExecute(Object result)
   {
	  if (isShowDialog)
	  {
		 UtiDialog.getInstance().DismissLoadingDialog();
	  }
	  try
	  {
		 if (result != null)
		 {
			DJson data = (DJson) result;
			if (!data.getHead().hasError())
			{
			   final UpdateInfo info = new UpdateInfo();
			   info.setUrl(data.getBody().optString("download"));
			   info.setVersion(data.getBody().optString("version"));
			   info.setDescription(data.getBody().optString("trips"));
			   // if
			   // (Integer.valueOf(info.getVersion())>=Integer.valueOf(Session.getInstance().getVersion()))
			   if (!info.getVersion().equals(Session.getInstance().getVersion()))
			   {
				  DialogInterface.OnClickListener clickListener = new OnClickListener()
				  {
					 @Override
					 public void onClick(DialogInterface dialog, int which)
					 {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(info.getUrl()));
						context.startActivity(intent);
					 }
				  };
				  UtiDialog.getInstance().ShowOKCancelAlertDialog(context, "发现新版本是否下载?", info.getDescription(), clickListener);
			   }
			   else
			   {
				  if (isShowDialog)
				  {
					 UtiDialog.getInstance().ShowToastInfoShort(context, "恭喜您，当前已经是最新版本");
				  }
			   }
			}
			else
			{
			   UtiDialog.getInstance().ShowToastInfoShort(context, data.getHead().getRspMsg());
			}
		 }
		 else
		 {
			if (isShowDialog)
			{
			   UtiDialog.getInstance().ShowToastInfoShort(context, "网络异常请稍候再试");
			}
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "TaskCheckVersion_onPostExecute(result) " + e);
	  }
   }
}
